package com.piece.core.mongo.context;

import com.piece.core.framework.support.dto.StreamBlockDTO;
import com.piece.core.framework.util.math.SequenceUtil;
import com.piece.core.framework.service.StreamBlockService;
import com.piece.core.log.config.RequestContextHolder;
import com.piece.core.mongo.entity.MongoStreamBlock;
import com.piece.core.mongo.service.MongoStreamBlockService;
import com.piece.core.framework.util.object.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component("streamBlockService")
public class StreamBlockServiceMongoImpl implements StreamBlockService {

    @Resource
    private MongoStreamBlockService mongoStreamBlockService;

    @Override
    public void save(String ip) {
        ip = null == ip ? RequestContextHolder.get().getIp() : ip;
        MongoStreamBlock streamBlock = new MongoStreamBlock();
        streamBlock.setId(SequenceUtil.uuid());
        streamBlock.setIp(ip);
        streamBlock.setCity(RequestContextHolder.get().getCity());
        streamBlock.setArea(RequestContextHolder.get().getArea());
        streamBlock.setBlockTime(new Date());
        mongoStreamBlockService.insert(streamBlock);
    }

    @Override
    public void delete(String ip) {
        mongoStreamBlockService.deleteByIp(ip);
    }

    @Override
    public List<StreamBlockDTO> queryByIp(String ip) {
        List<MongoStreamBlock> streams = mongoStreamBlockService.findByIp(ip);
        List<StreamBlockDTO> result = streams.stream().map(stream -> {
            StreamBlockDTO blockDTO = new StreamBlockDTO();
            try {
                BeanUtil.copyProperties(stream, blockDTO);
            } catch (Exception e) {}
            return blockDTO;
        }).collect(Collectors.toList());

        return result;
    }
}
